const app = getApp();
let listCnt = 0;
let yCnt = 0;
let increment_totle = 0;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    isLogin: false,
    isTestStart:false,
    arrayTestType: ['英语一', '英语二'],
    arrayTestYear: [ '2025', '2024', '2023', '2022', '2021', '2020', '2019', '2018', '2017', '2016', '2015', '2014', '2013', '2012', '2011'],
    index: 1,
    indexyear:0,
    progress: 0,
    wordList: [],
//    answer:'',
    aone:'',
    atwo:'',
    displayone:'',
    displaytwo:'',
//    isAnswered:false,
    isPressed1:false,
    isPressed2:false,
    word:'',
  },
  pickerTestTypeChange: function(e) {
    this.setData({
      index: e.detail.value
    })
  },
  pickerTestYearChange: function(e) {
    this.setData({
      isTestStart: e.detail.value
    })
  },
  startTest(){
    listCnt = 0;
    yCnt = 0;
    let findwordUrl = app.globalData.baseUrl + 'api/testlist/'
    const that = this; // 将 this 赋值给 that
    // 查询
    wx.request({
      url: findwordUrl, // 后台API
      data: {
        test_type:this.data.index,
        test_year:this.data.arrayTestYear[this.data.indexyear],
        openid:wx.getStorageSync('openid')
      },
      method:'POST',
      header: {
        'content-type': 'application/json' // 默认值
      },
      /* 登录成功 */
      success (res){
        // 结果查询成功
        if(res.statusCode == 200){
          that.setData({
            isTestStart: true, 
            progress: 0, // 更新进度        
          })
          // 打乱list的顺序
          let wordlist = res.data.wordlist
          for (let i = wordlist.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1)); // 生成一个随机索引
            [wordlist[i], wordlist[j]] = [wordlist[j], wordlist[i]]; // 交换元素
          }
          that.setData({
            wordList:wordlist,
          }) 
          that.startTestLoop(wordlist);           
        }else{
          that.setData({
            isTestStart: false   
          })          
        }             
      },
      /* 登录失败 */
      fail:(err)=>{
        that.setData({ 
          isTestStart: false       
        })
      }
    })
    
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let isLoggedIn = getApp().globalData.isLoggedIn
    if(isLoggedIn){
      this.setData({
        isLogin: true
      });
    }else{
      this.setData({
        isLogin: false
      });  
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  startTestLoop: function (wordList) {
    if(wordList.length === 0){
      return;
    }
    const that = this; // 将 this 赋值给 that
    let interval = 300; // 更新间隔 (毫秒)
    let totleTime = 0;
    if(wordList.length>10){
      totleTime = 6500*10+3500*(wordList.length-10)
    }else{
      totleTime = 6500*wordList.length      
    }
    let atLine = listCnt;
    let increment = 0;
    

    let timer = setInterval(() => {
      increment +=100;
      if(listCnt > wordList.length-1){
        let currentProgress = 0; // 进度清空
        this.setData({
          progress: currentProgress.toFixed(0), // 更新进度
          wordList: wordList, // 答案更新
        });
        clearInterval(timer); // 停止计时器  
        let result = Math.floor((yCnt/wordList.length)*100);
        let msg = '本次考试成绩：'+result+' 分 \n'+'是否提交本次考试成绩？'
        wx.showModal({
          title: '考试结束',
          content: msg,
          success (res) {
            if (res.confirm) {
              // 提交成绩
              let submitResultUrl = app.globalData.baseUrl + 'api/submitresult/'
              wx.request({
                url: submitResultUrl, // 后台API
                data: {
                  wordList:that.data.wordList,
                  test_point:result,
                  test_type:that.data.index,
                  test_year:that.data.arrayTestYear[that.data.indexyear],
                  openid:wx.getStorageSync('openid')
                },
                method:'POST',
                header: {
                  'content-type': 'application/json' // 默认值
                },
                /* 成绩提交成功 */
                success (res){
                  // 成绩提交成功
                  if(res.statusCode == 200){
                    wx.showToast({
                      icon:'success‌',
                      title: '提交成功！',
                      content: '考试成绩提交成功离上岸又近一步！',
                    })                           
                  }else{ 
                    wx.showToast({
                      icon:'error',
                      content: '成绩提交失败了！\n要不你联系一下麻椒试试？\n13842866786（WX同步）',
                    })       
                  }             
                },
                /* 考试成绩失败 */
                fail:(err)=>{
                  wx.showToast({
                    icon:'error',
                    content: '成绩提交失败了！\n要不你联系一下麻椒试试？\n13842866786（WX同步）',
                  })
                }
              })
            } else if (res.cancel) {
            }
          }
        }) 
        this.setData({
          isTestStart:false,
        });
        return     
      }
      
      if(increment === 100 || atLine < listCnt){
        // 题目显示到画面
        const randomNumber = Math.floor(Math.random() * 2) + 1;
        if(randomNumber===1){  
          this.setData({
            word:wordList[listCnt][4],
            aone:'1',
            displayone:wordList[listCnt][5],
            atwo:'0',
            displaytwo:wordList[listCnt][6],  
          })
        }else{
          this.setData({
            word:wordList[listCnt][4],
            aone:'0',
            displayone:wordList[listCnt][6],
            atwo:'1',
            displaytwo:wordList[listCnt][5],
          })
        } 
        atLine = listCnt;
        this.startProgress(wordList); 
      }          
    }, interval);
  },
  startProgress: function (wordList) {
    let atLine = 0;
    let totleTime = 0;
    if(listCnt < 10){
      totleTime = 6000;
    }else{
      totleTime = 3000;
    }
    let interval = 1000; // 更新间隔 (毫秒)
    let duration = totleTime; // 总时长 (毫秒)
    let increment = 100 / (duration / interval); // 每次增加的进度

    let currentProgress = 0; // 当前进度

    let timer = setInterval(() => {
      currentProgress += increment;

      if (currentProgress >= 100) {
        currentProgress = 100;
        // 将答案保存        
        if(listCnt < wordList.length){
          this.setData({
            wordList : wordList,
            isPressed1 : false,
            isPressed2 : false,
          })
          listCnt++
        } 
        clearInterval(timer); // 停止计时器
      }

      this.setData({
        progress: currentProgress.toFixed(0), // 更新进度
      });
    }, interval);
  },
  answerfun1:function(e){
    const value = e.currentTarget.dataset.value;
    let wordList = this.data.wordList;
    wordList[listCnt][7] = value;
    if(listCnt < wordList.length-1){
      this.setData({
        wordList : wordList,
      })
    } 
    if(value === '1'){
      yCnt++;      
    }
    this.setData({
      isPressed1 : true,
      isPressed2 : false,
    })       
  },
  answerfun2:function(e){
    const value = e.currentTarget.dataset.value;
    let wordList = this.data.wordList;
    wordList[listCnt][7] = value;
    if(listCnt < wordList.length-1){
      this.setData({
        wordList : wordList,
      })
    } 
    if(value === '1'){
      yCnt++;      
    }
    this.setData({
      isPressed1 : false,
      isPressed2 : true,
    })       
  }
})